package com.xwaf.platform.web.controller.auth;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xwaf.platform.common.api.CommonResponse;
import com.xwaf.platform.common.api.constants.BaseConstants;
import com.xwaf.platform.common.api.constants.RedisKeys;
import com.xwaf.platform.common.api.entity.ELUser;
import com.xwaf.platform.common.redis.util.RedisUtil;
import com.xwaf.platform.common.web.BaseController;
import com.xwaf.platform.system.api.entity.DataBase;
import com.xwaf.platform.system.api.entity.auth.Dictionary;
import com.xwaf.platform.system.api.service.auth.DictionaryService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * <p>
 * 字典
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2019-5-30 16:02:40 <br>
 * @see 无<br>
 *      Copyright (c) 2019, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@RestController
@Api(tags = "字典")
@RequestMapping(value = "/m/dictionary/")
public class DictionaryController extends BaseController {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private DictionaryService dictionaryService;

	@ApiOperation(value = "分页查询", response = Dictionary.class)
	@PostMapping(value = "page", produces = "application/json;charset=UTF-8")
	public CommonResponse page(@RequestParam("currentPage") String currentPage,
			@RequestParam("pageSize") String pageSize, @RequestBody Dictionary dictionary) {
		CommonResponse resp = CommonResponse.createCommonResponse();
		if (!StringUtils.isNotBlank(currentPage) & !StringUtils.isNotBlank(pageSize)) {
			currentPage = "1";
			pageSize = "10";
		}
		Page<Dictionary> page = new Page<Dictionary>(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
		Page<Dictionary> result = dictionaryService.selPageList(page, dictionary);
		resp.setData(result);
		return resp;
	}

	@ApiOperation(value = "根据条件查询", notes = "根据条件查询信息", response = Dictionary.class, httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
	@GetMapping(value = "dictionarys", produces = "application/json;charset=UTF-8")
	public CommonResponse list(@RequestParam("name") String name) {
		Wrapper<Dictionary> wrapper = new EntityWrapper<Dictionary>();
		wrapper.like("name", name);
		List<Dictionary> list = dictionaryService.selectList(wrapper);
		return CommonResponse.createCommonResponse(list);
	}

	@SuppressWarnings("unchecked")
	@ApiOperation(value = "新增", notes = "新增信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@PostMapping(value = "add", produces = "application/json;charset=UTF-8")
	public CommonResponse addDictionary(@RequestBody Dictionary dictionary) {
		ELUser loginUser = getLoginUser();
		if (loginUser != null) {
			dictionary.setCreateBy(loginUser.getId());
			dictionary.setUpdateBy(loginUser.getId());
		}
		dictionary.setId(DataBase.getDataBaseId(DataBase.DY));
		boolean isAdded = dictionaryService.insert(dictionary);
		if (isAdded) {
			// 取缓存
			List<Dictionary> list = (List<Dictionary>) redisUtil.get(RedisKeys.SYS_DICT + dictionary.getConfigKey());
			if (list != null) {
				list.add(dictionary);
			} else {
				list = new ArrayList<Dictionary>();
				list.add(dictionary);
			}
			// 存缓存
			redisUtil.set(RedisKeys.SYS_DICT + dictionary.getConfigKey(), list);
			return CommonResponse.createCommonResponse(dictionary);
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "新增失败!");
		}
	}

	@SuppressWarnings("unchecked")
	@ApiOperation(value = "修改", notes = "修改信息", httpMethod = "PUT", produces = MediaType.APPLICATION_JSON_VALUE)
	@PutMapping(value = "update/{dictionaryId}", produces = "application/json;charset=UTF-8")
	public CommonResponse updateDictionary(@PathVariable("dictionaryId") String dictionaryId,
			@RequestBody Dictionary dictionary) {
		ELUser loginUser = getLoginUser();
		if (loginUser != null) {
			dictionary.setUpdateBy(loginUser.getId());
		}
		dictionary.setId(dictionaryId);
		boolean isUpdated = dictionaryService.updateById(dictionary);
		if (isUpdated) {
			// 取缓存
			List<Dictionary> list = (List<Dictionary>) redisUtil.get(RedisKeys.SYS_DICT + dictionary.getConfigKey());
			for (Dictionary dict : list) {
				if (dictionary.getId().equals(dict.getId())) {
					list.remove(dict);
					list.add(dictionary);
					break;
				}
			}
			// 存缓存
			redisUtil.set(RedisKeys.SYS_DICT + dictionary.getConfigKey(), list);
			return CommonResponse.createCommonResponse();
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "修改失败!");
		}
	}

	@ApiOperation(value = "删除", notes = "删除信息", httpMethod = "DELETE", produces = MediaType.APPLICATION_JSON_VALUE)
	@DeleteMapping(value = "delete/{dictionaryIds}", produces = "application/json;charset=UTF-8")
	public CommonResponse delById(@PathVariable("dictionaryIds") List<String> dictionaryIds) {
		boolean isDel = dictionaryService.deleteBatchIds(dictionaryIds);
		if (isDel) {
			for (String key : dictionaryIds) {
				// redisUtil.remove(RedisKeys.SYS_DICT + key);
			}
			return CommonResponse.createCommonResponse();
		} else {
			return CommonResponse.createCustomCommonResponse(BaseConstants.FAIL.getCode(), "删除失败!");
		}
	}

	@ApiOperation(value = "查看详情", notes = "查看详情信息", httpMethod = "GET", response = Dictionary.class, produces = MediaType.APPLICATION_JSON_VALUE)
	@GetMapping(value = "info/{dictionaryId}", produces = "application/json;charset=UTF-8")
	public CommonResponse getInfoById(@PathVariable("dictionaryId") String dictionaryId) {
		Dictionary dictionary = dictionaryService.selectById(dictionaryId);
		return CommonResponse.createCommonResponse(dictionary);
	}

	@ApiOperation(value = "根据key删除redis缓存", notes = "根据key删除redis缓存", httpMethod = "DELETE", produces = MediaType.APPLICATION_JSON_VALUE)
	@DeleteMapping(value = "/redis/{key}", produces = "application/json;charset=UTF-8")
	public CommonResponse delRedisDic(@PathVariable("key") String key) {
		redisUtil.remove(key);
		return CommonResponse.createCommonResponse();
	}

	@ApiOperation(value = "根据key查数据字典", notes = "根据key查数据字典", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
	@GetMapping(value = "/getByKey/{configKey}", produces = "application/json;charset=UTF-8")
	public CommonResponse getByKey(@PathVariable("configKey") String configKey) {
		Dictionary dictionary = new Dictionary();
		dictionary.setConfigKey(configKey);
		List<Dictionary> list = dictionaryService.getRediesByKey(configKey);
		if (list.size() > 0 && list != null) {
			return CommonResponse.createCommonResponse(list);
		} else {
			return CommonResponse.createCommonResponse(new ArrayList<>());
		}
	}

}
